package priv.wjh.study.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

public class NioServer {

    // 通道管理器(Selector)
    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();


    public static void main(String[] args) throws IOException {
        // 创建通道管理器(Selector)
        Selector selector = Selector.open();
        // 创建通道ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.configureBlocking(false);
        ServerSocket socket = serverSocketChannel.socket();
        socket.bind(new InetSocketAddress(10001));

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true){
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    handlerAccept(key);
                }
            }
        }
    }


    private static void handlerAccept(SelectionKey key) throws IOException {
        SelectableChannel channel = key.channel();
        if (channel instanceof ServerSocketChannel serverSocketChannel){
            final int i = ATOMIC_INTEGER.incrementAndGet();
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);
            Executors
                    .newSingleThreadExecutor((Runnable r) -> new Thread(r, i +" thread"))
                    .submit(() -> {
                try {
                    Selector selector = Selector.open();
                    // 信息通过通道发送给客户端
                    String msg = "Hello Client!";
                    socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    while (true){
                        int select = selector.select(1000);
                        Set<SelectionKey> selectionKeys = selector.selectedKeys();
                        Iterator<SelectionKey> iterator = selectionKeys.iterator();
                        while (iterator.hasNext()){
                            SelectionKey readableKey = iterator.next();
                            iterator.remove();
                            if (readableKey.isReadable()){
                                handlerRead(String.valueOf(i), readableKey);
                            }
                        }
                        if (select == 0){
                            System.out.println("time out");
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            });
        }
    }

    private static void handlerRead(String prefix, SelectionKey key) throws IOException {
        SelectableChannel channel = key.channel();
        if (channel instanceof SocketChannel socketChannel){
            // 从通道读取数据到缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(128);
            socketChannel.read(buffer);
            // 输出客户端发送过来的消息
            byte[] data = buffer.array();
            String msg = new String(data).trim();
            System.out.println(prefix +" server received msg from client：" + msg);
        }
    }
}
